#include "Buffer.h"

#include <errno.h>
#include <sys/uio.h>
#include <unistd.h>
// 从fd上读取数据
ssize_t Buffer::readFd(int fd, int *saveErrno)
{
    char extraBuf[65536] = {0}; // 栈内存
    struct iovec vec[2];
    const size_t writable = writableBytes(); // 剩余可写空间大小
    vec[0].iov_base = begin() + writeIndex_;
    vec[0].iov_len = writable;

    vec[1].iov_base = extraBuf;
    vec[1].iov_len = sizeof extraBuf;

    const int iovcnt = (writable < sizeof extraBuf) ? 2 : 1;
    const ssize_t n = ::readv(fd, vec, iovcnt);
    if (n < 0)
    { // 读取失败
        *saveErrno = errno;
    }
    else if (n <= writable)
    { // 读到数据，但小于剩余可写空间大小已经够了不需要使用第二段空间
        writeIndex_ += n;
    }
    else
    { // 读到数据，大于剩余可写空间大小
        writeIndex_ = buffer_.size();
        append(extraBuf, n - writable);
    }
    return n;
}

ssize_t Buffer::writefd(int fd, int *saveError)
{
    ssize_t n = ::write(fd, peek(), readableBytes());
    if (n < 0)
    {
        *saveError = errno;
    }
    return n;
}
